package com.iring.util.common;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;

import org.springframework.stereotype.Component;

import com.iring.exception.IringException;

/**
 * 通用工具
 *
 * @author wanggan
 */
@Component
public class CommonUtil {

    private static final String DOMAIN_PATTERN = "[0-9a-z]+.sip.iringtel.com";

    private static final String ORDER_PATTERN = "yyyyMMddHHmmss";

    private static final String EMAIL_PATTERN = "[0-9a-zA-Z_.]{1,}@[a-zA-Z0-9.]{1,}[a-zA-Z]{1,}";

    private static final String PHONE_PATTERN = "[0-9]{7,20}";

    private static final String MAC_PATTERN = "[0-9a-zA-Z]{12}";

    


    /**
     * 对电话号码进行处理,隐藏中间的部分电话
     *
     * @param contactPhone
     *          电话号码
     * @return  处理后的电话号码<pre>
     *     当输入的是86-18428326484,返回的样例:+ 86 184****6494
     * </pre>
     */
    public  String dealContactPhoneNumber(String contactPhone) {
        if(contactPhone.contains("-")) {
            return contactPhone.replaceAll("(\\d{1,})-(\\d{3})\\d{0,}(\\d{4})", "+$1 $2****$3");
        }
        throw new IringException("invalid phone number");
    }

    /**
     * 正则匹配是否匹配规则
     *
     * @param domain
     *          ddns域名
     * @return  是否匹配,如果匹配<code>true</code>
     * 如果不匹配<code>false</code>
     */
    public Boolean checkDeviceDomain(String domain){
        return Pattern.matches(DOMAIN_PATTERN, domain);
    }

    public String getOrderid(){
        LocalDateTime localDateTime = LocalDateTime.now();
        String orderid = localDateTime.format(DateTimeFormatter.ofPattern(ORDER_PATTERN))+StringUtil.getRandomNumberStr(4);
        return orderid;
//        Boolean isSuccess = false;
//
//        for(int i = 0;i < 2;i++){
//            PayOrder payOrder = payOrderDao.findDistinctByOrderId(orderid);
//            if(null == payOrder){
//                isSuccess = true;
//                break;
//            }
//            orderid = localDateTime.format(DateTimeFormatter.ofPattern(ORDER_PATTERN))+StringUtil.getRandomNumberStr(4);
//        }
//        if(isSuccess){
//            return orderid;
//        }
//        return null;
    }


    /**
     * 检查邮箱或者用户名
     *
     * @param email
     *          邮箱用户名
     * @return  是否合法
     */
    public Boolean checkEmail(String email){
        return Pattern.matches(EMAIL_PATTERN, email);
    }

    public Boolean checkPhone(String phone){
        return Pattern.matches(PHONE_PATTERN, phone);
    }

    public Boolean checkMac(String mac){
        return Pattern.matches(MAC_PATTERN,mac);
    }
}
